package com.googlecode.nls4j;

import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;

/**
 * An implementation of {@linkplain NlsBundle} which does not have any internal
 * storage and the method {@linkplain #get(NlsKey)} always returns
 * {@code key.getDefaultValue(getLocale())}.
 * 
 * @author Andrey Pavlenko
 */
public class DefaultValuesBundle<K extends NlsKey<V>, V> implements
        NlsBundle<K, V> {
    private static final ConcurrentHashMap<Locale, DefaultValuesBundle<?, ?>> cache = new ConcurrentHashMap<Locale, DefaultValuesBundle<?, ?>>();
    private final Locale locale;

    /**
     * Create new instance with the specified locale.
     */
    public DefaultValuesBundle(final Locale locale) {
        this.locale = locale;
    }

    /**
     * Retrieves a DefaultValuesBundle instance with the specified locale from
     * the internal cache. If there is no such instance in the cache, it will be
     * created and cached.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static <K extends NlsKey<V>, V> DefaultValuesBundle<K, V> getInstance(
            final Locale locale) {
        DefaultValuesBundle b = cache.get(locale);

        if (b == null) {
            b = new DefaultValuesBundle(locale);
            final DefaultValuesBundle b1 = cache.putIfAbsent(locale, b);
            return (b1 != null) ? b1 : b;
        }

        return b;
    }

    /**
     * Clears the internal cache of DefaultValuesBundle instances.
     */
    public static void clearCache() {
        cache.clear();
    }

    /**
     * {@inheritDoc}<br/>
     * This implementation always returns
     * {@code key.getDefaultValue(getLocale())}.
     */
    @Override
    public V get(final K key) {
        return key.getDefaultValue(getLocale());
    }

    /**
     * {@inheritDoc}<br/>
     * This implementation always returns {@code true}.
     */
    @Override
    public boolean contains(final K key) {
        return true;
    }

    @Override
    public Locale getLocale() {
        return locale;
    }
}
